package com.example.gfile.random;

import com.example.gfile.entity.Filed;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

@Service
public class DatabaseColumn implements IRandomData {

    private static Map<String, List<List<Map<String, Object>>>> dbColumnList = new HashMap<>();

    public static void setDbColumnList(Map<String, List<List<Map<String, Object>>>> dbColumnList) {
        DatabaseColumn.dbColumnList = dbColumnList;
    }

    @Override
    public String type() {
        return DB_COLUMN_TYPE;
    }

    @Override
    public Function<Filed, String> data() {
        return filed -> {
            String dbId = filed.getSqlId();
            List<List<Map<String, Object>>> lists = dbColumnList.get(dbId);
            int index = filed.getLineIndex();
            String column = filed.getColumn();
            if (!CollectionUtils.isEmpty(lists)) {
                if (index >= lists.size()) {
                    int random = RandomUtils.nextInt(0, lists.size());
                    return String.valueOf(lists.get(random).get(0).get(column));
                } else {
                    return String.valueOf(lists.get(index).get(0).get(column));
                }
            }
            return StringUtils.EMPTY;
        };
    }
}
